package spatialmarketplace.cem.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.*;
import spatialmarketplace.cem.dao.AttachmentDao;
import spatialmarketplace.cem.dao.DBHandler;
import spatialmarketplace.cem.dao.implementation.AttachmentDaoImpl;
import spatialmarketplace.cem.model.Attachment;
import spatialmarketplace.cem.model.Group;
import spatialmarketplace.cem.model.GroupMember;
import spatialmarketplace.cem.model.User;

/**
 * Class that manage the business logic of Create Groups
 * @author Laura Andreina
 */
public class CreateGroupFormActionBean extends GroupActionBean {

    private static final Log logger = Log.getInstance(CreateGroupFormActionBean.class);
    private static final String FORM = "/WEB-INF/jsp/creategroup_form.jsp";
    /***********************************************************/
    /* Setting the path to upload files when a group is created*/
    /***********************************************************/
    private static final String fullPath = "C:/Users/Laura Andreina/Documents/NetBeansProjects/SpatialMarketplace/web/";
    private FileBean attachment;
    private List<User> users = new ArrayList<User>();
    private String userList;

    /*
     * The default event handler is triggered when an event handler is not
     * specified An event handler is a method that does the following: 
     *  * Is declared as public 
     *  * Returns a Resolution 
     *  * Takes no parameters 
     *  * Is defined in an action bean
     */
    @DefaultHandler
    public Resolution form() {
        return new ForwardResolution(FORM);
    }

    public AttachmentDao getAttachmentDao() {
        return attachmentDao;
    }

    public void setAttachmentDao(AttachmentDao attachmentDao) {
        this.attachmentDao = attachmentDao;
    }

    public String getUserList() {
        return userList;
    }

    public void setUserList(String userList) {
        this.userList = userList;
    }

    /*
     * To get the list of members to be add when a group is created @return List
     * <User>
     */
    public List<User> getUsersList() {
        List<User> usersTemp = new ArrayList<User>();
        Integer usrId = getContext().getUserId();
        try {

            usersTemp = getGroupDao().readUsers(usrId);

        } catch (Exception e) {
            ValidationError error = new SimpleError(usersTemp + " The list of users cannot be displayed. Please try later.");
            getContext().getValidationErrors().add("users ", error);
            logger.error("Error" + e);
            System.out.println("Error: " + CreateGroupFormActionBean.class.getName() + ", " + e);
        }
        return usersTemp;

    }

    public void setUsersList(List<User> users) {
        this.users = users;
    }

    /*
     * To save a new group @return new RedirectResolution()
     */
    public Resolution save() throws Exception {
        Group group = getGroup();
        String path = "";
        String fileName = "";
        Integer groupIdSaved = null;
        attachment = group.getFile();
        User user = new User();
        List<User> userList2 = new ArrayList<User>();
        String usersIds = getUserList();
        String[] tokens;

        try {
            if (attachment != null) {
                fileName = attachment.getFileName();
                if (attachment.getSize() > 0) {
                    //attachment treatment
                    path = addAttachment(attachment);
                } else {
                    ValidationError error = new SimpleError(attachment.getFileName() + " is not a valid file.");
                    getContext().getValidationErrors().add("attachments", error);
                    logger.error("ERROR: " + error);
                }
                //setting up the logo path
                group.setLogo(path);
            }
            if (group.getName().equals("") || group.getDescription().equals("")
                    || group.getKeyword().equals("")) {

                ValidationError error = new SimpleError("There are blank fields. The group cannot be created.");
                getContext().getValidationErrors().add("group ", error);
                logger.error("ERROR: " + error);

            } else {
                //saving the new group
                groupIdSaved = getGroupDao().save(group);
                getContext().getMessages().add(new SimpleMessage("The group " + group.getName() + " has been saved."));
            }

            //saving the members added to the new group if are added. 
            //By default is added the user who created the group

            if (groupIdSaved != null) {
                /*
                 * always adding the user logged into the app
                 */
                user.setUserId(getContext().getUserId());
                userList2.add(user);

                if (usersIds.equals("memberListEmpty")) {
                    /*
                     * ONLY is inserted the logged user, that is, the user who
                     * creates the group if no members are added
                     */
                    getGroupDao().saveGroupMembers(userList2, groupIdSaved,getContext().getUserId());
                } else {
                    tokens = usersIds.split(",");
                    for (int i = 0; i < tokens.length; i++) {
                        user = new User();
                        user.setUserId(Integer.parseInt(tokens[i]));
                        userList2.add(user);
                    }
                    getGroupDao().saveGroupMembers(userList2, groupIdSaved, getContext().getUserId());
                }
            } else {
                ValidationError error = new SimpleError(group + " The members information cannot be saved.");
                getContext().getValidationErrors().add("group", error);
                logger.error("Error" + error);
            }


        } catch (Exception e) {
            ValidationError error = new SimpleError(users + " The list of users cannot be displayed. Please try later.");
            getContext().getValidationErrors().add("users ", error);
            logger.error("Error" + e);
            System.out.println("Error: " + CreateGroupFormActionBean.class.getName() + ", " + e);

        }
        return new RedirectResolution(WelcomeScreenActionBean.class);
    }

    /*
     * Cancel the action of create group @return new RedirectResolution()
     */
    @DontValidate
    public Resolution cancel() {
        getContext().getMessages().add(
                new SimpleMessage("Action cancelled."));
        return new RedirectResolution(WelcomeScreenActionBean.class);
    }

    /*
     * Validating fields
     */
    @ValidateNestedProperties({
        @Validate(field = "name", required = true, on = "save"),
        @Validate(field = "description", required = true, on = "save"),
        @Validate(field = "keyword", required = true, on = "save"),})
    @Override
    public void setGroup(Group group) {
        super.setGroup(group);
    }

    /*
     * To add Attachtment field when a group is created @param FileBean @return
     * String
     */
    private String addAttachment(FileBean fileBean) throws Exception {
        Attachment attachment = new Attachment();
        String filePath;

        attachment.setFileName(fileBean.getFileName());
        attachment.setContentType(fileBean.getContentType());
        attachment.setSize(fileBean.getSize());

        attachmentDao.save(attachment);
        filePath = attachmentDao.getFilePath(attachment);
        fileBean.save(new File(fullPath + filePath));
        return filePath;
    }
    private AttachmentDao attachmentDao = AttachmentDaoImpl.getInstance();

    public FileBean getAttachment() {
        return attachment;
    }

    public void setAttachment(FileBean attachment) {
        this.attachment = attachment;
    }

    public List<User> getUsers() {

        return getUsersList();
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}
